package cn.learn.validate;

import cn.learn.properties.MySecurityConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码的请求接口
 *
 * @author huangyezhan
 * @date 2020年2月18日15:29:33
 */
@RestController
public class ValidateCodeController {
    private static final Logger logger = LoggerFactory.getLogger(ValidateCodeController.class);

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    /**
     * 创建验证码，根据不同的类型获验证码，调用不同的 {@link ValidateCodeProcessor} 接口实现
     *
     * @param request  请求
     * @param response 响应
     * @param type     请求验证码的类型（短信、图形文字等）
     * @throws Exception
     */
    @RequestMapping(value = MySecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}", method = RequestMethod.GET)
    public void createCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) throws Exception {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            validateCodeProcessorHolder.findValidateCodeProcessor(type).createCode(request,response);
        } catch (ValidateCodeException e) {
            logger.info("请求验证码错误：{}",e.getMessage());
            response.getWriter().write(e.getMessage());
        }catch (Exception e){
            logger.info("创建验证码错误：",e);
            response.getWriter().write(e.getMessage());
        }
    }


}
